<template>
  <div class="main-app">
    <el-row style="margin-top: 10px">
      <el-form ref="form" :model="form" :rules="rules" label-width="220px">
        <el-col :span="11">
          <!-- <el-form-item label="车辆名称:" prop="name">
            <el-input v-model="form.name" :disabled="isView" clearable />
          </el-form-item> -->
          <el-form-item label="车牌号:" prop="plateNumber">
            <el-input v-model="form.plateNumber" :disabled="isView" />
          </el-form-item>

          <el-form-item label="车牌颜色:" prop="plateColor">
            <el-select v-model="form.plateColor" placeholder="请选择车牌颜色" :disabled="isView" clearable
              style="width: 100%;">
              <el-option v-for="item in licensePlateColorOptions" :key="item.value" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车辆类型:" prop="vehicleModel">
            <el-select v-model="form.vehicleModel" placeholder="请选择车辆类型" :disabled="isView" clearable
              style="width: 100%;">
              <el-option v-for="item in carOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="司机:" prop="drivers">
            <el-select v-model="form.drivers" placeholder="请选择司机" :disabled="isView" @change="driversChange" multiple
              clearable style="width: 100%;">
              <el-option v-for="item in driverOptions" :key="item.guid" :label="item.name" :value="item.guid">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="司机电话:">
            <el-input v-model="form.driverPhone" disabled />
          </el-form-item>
          <el-form-item label="押运员:" prop="escorts">
            <el-select v-model="form.escorts" placeholder="请选择押运员" :disabled="isView" @change="escortsChange" multiple
              clearable style="width: 100%;">
              <el-option v-for="item in escortOptions" :key="item.guid" :label="item.name" :value="item.guid">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="押运员电话:">
            <el-input v-model="form.escortPhone" disabled />
          </el-form-item>
          <el-form-item v-if="!isView" label="车辆图片:">
            <el-upload action="" class="upload-demo" :on-preview="hwblPicTureCardPreview"
              :on-remove="hwblPicHandleRemove" :on-change="hwblPicHandleChangeLi" :auto-upload="false"
              :file-list="imageObjList">
              <el-button size="small" type="primary">点击添加</el-button>
            </el-upload>
            <!-- <el-dialog :visible.sync="ImageVisible">
              <img width="100%" :src="form.dialogImageUrl" alt="">
            </el-dialog> -->
          </el-form-item>
          <el-form-item v-else label="车辆图片:">
            <el-button type="primary" icon="el-icon-view" @click="
              ViewFile(
                '车辆图片',
                `${form.vehicleImgUrlList}`
              )
            ">
              点击查看</el-button>
          </el-form-item>


          <el-form-item label="备注:">
            <el-input type="textarea" :rows="3" v-model="form.remark" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="外部尺寸:" prop="externalDimensions">
            <el-input v-model="form.externalDimensions" :disabled="isView" clearable />
          </el-form-item>
          <el-form-item label="强制报废期止:" prop="eomrpTime">
            <el-date-picker v-model="form.eomrpTime" type="date" placeholder="选择日期" :disabled="isView"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="核定载质量:" prop="approvedLoadMass">
            <el-input-number v-model="form.approvedLoadMass" :disabled="isView" clearable />
          </el-form-item>
          <el-form-item label="核定载人数:">
            <el-input-number v-model="form.authorizedCapacity" :disabled="isView" clearable />
          </el-form-item>
          <el-form-item label="总质量(kg):">
            <el-input-number v-model="form.totalMass" :disabled="isView" clearable />
          </el-form-item>
          <el-form-item label="整备质量(kg):">
            <el-input-number v-model="form.curbWeight" :disabled="isView" clearable />
          </el-form-item>

          <el-form-item label="档案编号:">
            <el-input v-model="form.archivesNumber" :disabled="isView" clearable />
          </el-form-item>
          <el-form-item label="发动机号码:">
            <el-input v-model="form.engineNumber" :disabled="isView" clearable />
          </el-form-item>
          <el-form-item label="使用状态:">
            <el-radio-group v-model="form.useStatus" :disabled="isView">
              <el-radio label="0">启用</el-radio>
              <el-radio label="1">未启用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <el-row style="margin-top: 40px; text-align: center">
      <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="primary" @click="save" :disabled="isView">提交</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-row>


    <div class="dialog_diy">
      <el-dialog :visible.sync="dialogVisible" width="70%" style="margin-top: -100px" @close="closeDialog">
        <div slot="title" style="background: #1890ff; color: white">
          <div style="padding: 15px 20px">{{ picTitle }}</div>
        </div>
        <el-form ref="form" style="margin-top: 15px" :model="form">
          <div class="block">
            <el-carousel height="700px" style="text-align: center">
              <!--  <img src="../../../../assets/401_images/401.gif"> -->
              <el-carousel-item v-for="item in urls" :key="item">


                <el-image style="height: 100%; width: 100%" fit="scale-down" :src="item" />
              </el-carousel-item>
            </el-carousel>
          </div>
          <el-row style="margin-top: 20px; text-align: center">
            <el-form :inline="true" class="form-inline">
              <el-form-item>
                <el-button @click="closeDialog">返 回</el-button>
              </el-form-item>
            </el-form>
          </el-row>
        </el-form>
      </el-dialog>


    </div>
  </div>
</template>

<script>
  import {
    CarType,
    LicensePlateColor
  } from "../../../../utils/resource";
  import {
    save,
    getById,
    UpdateVehicleImg
  } from "../../../../api/vehicle";
  import {
    GetAllUserLists
  } from "../../../../api/user";


  export default {
    data() {
      return {
        imageObjList: [],
        imageObjList_Del: [],
        urls: [
          // "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
        ],
        ImageVisible: false,

        picTitle: "图片详情",
        dialogVisible: false,


        carOptions: CarType,
        licensePlateColorOptions: LicensePlateColor,
        driverOptions: [{
            driverId: "111",
            driverName: "222",
          },
          {
            driverId: "333",
            driverName: "444",
          },
        ],
        escortOptions: [{
            escortId: "555",
            escortName: "666",
          },
          {
            escortId: "777",
            escortName: "888",
          },
        ],
        form: {
          name: "",
          vehicleModel: "",
          plateNumber: "",
          plateColor: "",
          drivers: [],
          driverId: "",
          driverPhone: "",
          escorts: [],
          escortId: "",
          escortPhone: "",
          remark: "",
          archivesNumber: "",
          authorizedCapacity: 0,
          totalMass: 0,
          curbWeight: 0,
          approvedLoadMass: 0,
          externalDimensions: "",
          eomrpTime: "",
          engineNumber: "",
          useStatus: "0",
        },





























        rules: {
          name: [{
            required: true,
            message: "请输入车辆名称",
            trigger: "blur"
          }],
          vehicleModel: [{
            required: true,
            message: "请选择车辆类型",
            trigger: "change"
          }, ],
          plateNumber: [{
            required: true,
            message: "请输入车牌号",
            trigger: "blur"
          }, ],
          plateColor: [{
            required: true,
            message: "请选择车牌颜色",
            trigger: "change"
          }, ],
          drivers: [{
            type: "array",
            required: true,
            message: "请选择司机",
            trigger: "change",
          }, ],
          escorts: [{
            type: "array",
            required: true,
            message: "请选择押运员",
            trigger: "change",
          }, ],
          approvedLoadMass: [{
            required: true,
            message: "请输入核定载质量",
            trigger: "blur"
          }, ],
          externalDimensions: [{
            required: true,
            message: "请输入外部尺寸",
            trigger: "blur"
          }, ],
          eomrpTime: [{
            required: true,
            message: "请输入强制报废期止",
            trigger: "blur",
          }, ],
        },
        id: "",
        carId: "",
      };
    },
    computed: {
      isView() {
        return this.$route.name === "车辆详情";
      },
    },
    async mounted() {
      this.$refs["form"].resetFields();
      const {
        id,
        carId
      } = this.$route.params;
      const {
        data
      } = await GetAllUserLists({
        RoleCode: "SeriesR_Driver,SeriesR_Escort",
        "Status": "10",
        "Disabled": 0,
        "Wheres": ""
      });
      console.log(data);

      this.driverOptions = data;
      this.escortOptions = data;
      this.id = id;

      if (carId) {
        this.carId = carId;
        await this.getById(carId);
      }
    },
    methods: {
      /**
       * 文件发生改变时
       */
      hwblPicHandleChangeLi(file, fileList) {
        var obj = {
          id: "",
          file: file.raw,
          type: "3", // 更新类型 (1: 营业执照图片，2: 道路运输许可证图片)
          name: file.name,
          uid: file.uid,
          isDel: "0"
        }

        this.imageObjList.push(obj);
      },
      // 预览图片
      hwblPicTureCardPreview(file) {

        // this.dialogImageUrl = file.url;
        // this.ImageVisible = true;
      },
      // 删除图片
      hwblPicHandleRemove(file) {
        var obj = this.imageObjList.findIndex(item => {
          return item.uid === file.uid
        });
        if (obj >= 0) {
          if (this.imageObjList[obj].file) {
            this.imageObjList.splice(obj, 1);
          } else {
            this.imageObjList[obj].isDel = "1"; // 如果没有文件内容，说明此文件是从云上下载的
            this.imageObjList_Del.push(this.imageObjList[obj]);
            this.imageObjList.splice(obj, 1);
          }
        }
      },

      async ViewFile(title, url) {
        this.picTitle = title;

        if (url == "null" || url == null || url == "undefined") {
          this.$notify({
            title: "失败",
            message: "暂无图片！",
            type: "error",
            duration: 3000,
          });
        } else {
          this.urls = url.split(",");
          this.dialogVisible = true;
        }

      },
      closeDialog() {
        this.dialogVisible = false;
      },


      driversChange(value) {
        this.form.driverPhone = "";
        this.form.driverName = "";
        for (let p of value) {
          this.form.driverPhone += `${this.driverOptions.find((x) => x.guid === p).phone},`;
          this.form.driverName += `${this.driverOptions.find((x) => x.guid === p).name},`;
        }
        this.form.driverPhone = this.form.driverPhone.substring(0, this.form.driverPhone.lastIndexOf(','));
        this.form.driverName = this.form.driverName.substring(0, this.form.driverName.lastIndexOf(','));

      },
      escortsChange(value) {
        this.form.escortPhone = "";
        this.form.escortName = "";
        for (let p of value) {
          this.form.escortPhone += `${
   		  this.escortOptions.find((x) => x.guid === p).phone
   		},`;
          this.form.escortName += `${this.escortOptions.find((x) => x.guid === p).name},`;
        }
        this.form.escortPhone = this.form.escortPhone.substring(0, this.form.escortPhone.lastIndexOf(','));
        this.form.escortName = this.form.escortName.substring(0, this.form.escortName.lastIndexOf(','));
      },
      async getById(id) {
        const {
          data
        } = await getById(id);
        this.form = data;
        this.form.drivers = this.form.driverId.split(",");
        this.form.escorts = this.form.escortId.split(",");

        if (this.form.vehicleImgUrlList) {
          this.imageObjList = [];
          this.form.vehicleImgUrlList.forEach(item => {
            var List = item.split("/");
            var nameList = List[List.length - 1].split('?');
            var obj = {
              id: id,
              file: '',
              type: "2", // 更新类型 (1：车辆头像，2: 车辆图片，3: 资质附件图片)
              name: nameList[1],
              uid: nameList[0].split(".")[0],
              url: item,
              isDel: "0"
            }
            this.imageObjList.push(obj);
          })
        }
      },
      save(value) {
        this.$refs["form"].validate(async (valid) => {
          if (valid) {

            this.form.escortId = this.form.escorts.toString();
            this.form.driverId = this.form.drivers.toString();
            let data = Object.assign({
                orgGuid: this.id
              }, this.form),
              message = "";
            if (!this.carId) {
              message = "新增";
            } else {
              data = Object.assign({
                id: this.id
              }, data);
              message = "修改";
            }
            const {
              success,
              msg
            } = await save(data);
            if (success) {
              var imageFileList = [];
              this.imageObjList.forEach(item => {
                imageFileList.push(item);
              })
              this.imageObjList_Del.forEach(item => {
                imageFileList.push(item);
              })
              await this.UpdateVehicleImg(imageFileList, this.carId);


              this.$notify({
                title: "成功",
                message: `车辆${message}成功`,
                type: "success",
                duration: 3000,
              });
              this.$router.push(`/organization/transport/car/${this.id}`);
            } else {
              this.$notify({
                title: "失败",
                message: msg,
                type: "error",
                duration: 3000,
              });
            }

          } else {
            return false;
          }
        });
      },

      async UpdateVehicleImg(imageFileList, guid) {
        // 可以在for循环中使用异步函数，都执行完后才会执行下一个循环
        for (let i = 0; i < imageFileList.length; i++) {
          const imageFormData = new FormData();
          imageFormData.append('id', guid);
          imageFormData.append('type', imageFileList[i].type);
          imageFormData.append('file', imageFileList[i].file);

          imageFormData.append('name', imageFileList[i].name);
          imageFormData.append('uid', imageFileList[i].uid);
          imageFormData.append('isDel', imageFileList[i].isDel);

          await UpdateVehicleImg(imageFormData);
        }
      },

      cancel() {
        this.$router.push(`/organization/transport/car/${this.id}`);
      },
    },
  };
</script>
<style lang="scss" scoped>
  .dialog_diy {
    ::v-deep .el-dialog__wrapper {

      // eslint-disable-line
      .el-dialog {
        .el-dialog__body {
          padding: 0px;
        }

        .el-dialog__header {
          padding: 0px;
        }

        .el-dialog__headerbtn {
          top: 5px;
          right: 5px;
          padding-top: 10px;
        }

        .el-dialog__headerbtn .el-dialog__close {
          color: #fff;
          height: 30px;
          width: 35px;
        }

        .el-dialog__headerbtn .el-dialog__close:hover {
          color: gray;
        }
      }
    }
  }
</style>
